package com.yjps.house.service;

import com.yjps.common.page.Pager;
import com.yjps.common.util.CommonUtil;
import com.yjps.common.util.TimeUtil;
import com.yjps.house.dao.HistoryDao;
import com.yjps.house.dao.ShopApplyHistoryDao;
import com.yjps.house.dao.ShopDao;
import com.yjps.house.entity.ShopHistory;
import com.yjps.house.model.Shop;
import com.yjps.house.model.ShopApplyHistory;
import com.yjps.system.dao.AgentDao;
import com.yjps.system.dao.RoleDao;
import com.yjps.system.dao.UserDao;
import com.yjps.system.model.Agent;
import com.yjps.system.model.Role;
import com.yjps.system.model.User;
import com.yjps.system.service.RoleService;
import com.yjps.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

@Service("shopService")
public class ShopService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private AgentDao agentDao;

    @Autowired
    private HistoryDao historyDao;

    @Autowired
    private ShopDao shopDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private ShopApplyHistoryDao shopApplyHistoryDao;

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    public Shop findShop(int id) {
        return shopDao.load(id);
    }

    /**
     * 申请门店
     *
     * @param userId
     * @param reason
     * @param shop
     * @return
     */
    @Transactional
    public int applyShop(int userId, String reason, Shop shop) {
        shop.setUserId(userId);
        String time = TimeUtil.getCurrentTimeInString(TimeUtil.DATE_FORMAT_DATE);
        shop.setCreateTime(time);
        int shopId = shopDao.save(shop);
        ShopApplyHistory history = new ShopApplyHistory();
        history.setApplyUserId(userId);
        history.setApplyReason(reason);
        history.setTime(time);
        history.setShopId(shopId);
        /*---------*/
        //未处理
        history.setHandleResult(0);
        history.setIsValid(1);
        User user = roleService.findSystemManager();
        if(user != null)
           history.setHandleUserId(user.getId());
        else
           history.setHandleUserId(1);
        historyDao.save(history);

        return shopId;
    }

    /**
     * 门店申请列表
     *
     * @param startRow
     * @param pageSize
     * @return
     */
    @Transactional
    public List<ShopHistory> shopApplyList(int startRow, int pageSize) {
        String hql = "from ShopApplyHistory sh where sh.handleResult = null and isValid = 1";
        List<ShopApplyHistory> shs = historyDao.find(hql);
        List<ShopHistory> histories = new ArrayList<>();
        for (ShopApplyHistory sh : shs) {
            Shop shop = shopDao.get(sh.getShopId());
            ShopHistory history = new ShopHistory(sh.getApplyUserId(), sh.getApplyReason(), sh.getTime(), shop);
            histories.add(history);
        }
        return histories.subList(startRow, startRow + pageSize - 1);
    }

    /**
     * 审核门店
     *
     * @param userId
     * @param shopId
     * @param result
     */
    @Transactional
    public void verifyShop(int userId, int shopId, int result, int shopApplyHistoryId, int currentUserId) {
        String hql = "update ShopApplyHistory sh set sh.handleResult = :handleResult,sh.handleUserId = :handleUserId,sh.handleTime = :handleTime where sh.id =:id and isValid = 1";
        Map<String, Object> map = new HashMap<>();
        map.put("handleUserId", currentUserId);
        map.put("handleTime", CommonUtil.dataToString(new Date()));
        map.put("handleResult", result);
        map.put("id", shopApplyHistoryId);
        historyDao.excute(hql, map);
        if (result == 1) {
            //修改该用户为门店经理
            User user = userDao.load(userId);
            Map<String,Object> roleParams = new HashMap<>();
            String roleName = "Manager";
            String roleHql = "from Role r where r.isValid = 1 and r.rolename = :rolename";
            roleParams.put("rolename", roleName);
            Role r = roleDao.findUniqueResult(roleHql,roleParams);
            Set roleSet = new HashSet();
            roleSet.add(r);
            user.setRoles(roleSet);
            userService.updateUser(user);
            //修改门店状态 表示门店已被申请
            Shop shop = shopDao.load(shopId);
            if (shop != null) {
                shop.setUserId(user.getId());
                shop.setState(1);
                updateShop(shop);
            }

            /*Agent agent = new Agent();
            agent.setShopId(shopId);
            agent.setJoinTime(CommonUtil.dataToString(new Date()));
            agent.setUserId(userId);
            agent.setState(1);
            agent.setIsValid(1);
            agent.setAgentName("");
            agent.setDescription("");
            agent.setRemark("");
            agent.setScore("0");
            agent.setIcon("");
            agentDao.save(agent);*/

        }
    }

    /**
     * 更新门店
     *
     * @param shop
     */
    @Transactional

    public boolean updateShop(Shop shop) {
        String hql = "update Shop s set s.name = :name,s.logo = :logo," +
                "s.description= :description," +
                "s.remark =:remark,s.state = :state,s.userId = :userId where s.id = :id";
        Map<String, Object> params = new HashMap<>();
        params.put("name", shop.getName());
        params.put("logo", shop.getLogo());
        params.put("description", shop.getDescription());
        params.put("remark", shop.getRemark());
        params.put("state",shop.getState());
        params.put("userId",shop.getUserId());
        params.put("id", shop.getId());
        int affectRows = historyDao.excute(hql, params);
        if (affectRows == 0) {
            return false;
        }
        return true;
    }

    /**
     * 根据门店经理查询门店
     * @param userId
     * @return
     */
    @Transactional
    public Shop getShopByUserId(int userId) {
        String hql = "from Shop s where s.userId =:userId";
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        Shop shop = shopDao.findUniqueResult(hql, map);
        return shop;

    }



    /*
    public int addAgents(Agent agent,String userName){
        String hql="from User u where u.username =:userName";
        Map<String,Object> map=new HashMap<>();
        map.put("username",userName);
        User user=userDao.find(hql, map).get(0);
        agent.setUserId(user.getId());
        int agentId=agentDao.save(agent);
        return agentId;
    }*/

    /**
     * 分页查询门店申请列表
     *
     * @param pager
     * @param apply_hanlder_result
     * @return
     * @throws Exception
     */
    public Pager<ShopApplyHistory> getApplyByPager(Pager<ShopApplyHistory> pager, String apply_hanlder_result) throws Exception {
        Map<String, Object> params = new HashMap<>();
        String queryString = "from ShopApplyHistory t where t.isValid = 1";
        if (!StringUtils.isEmpty(apply_hanlder_result)) {
            queryString += " and t.handleResult =:handleResult";
            params.put("handleResult", Integer.parseInt(apply_hanlder_result));
        }
        queryString += " order by t.id desc";
        List<ShopApplyHistory> accounts = shopApplyHistoryDao.findWithSelect(queryString, params, (pager.getPageNo() - 1) * pager.getPageSize(), pager.getPageSize());
        pager.setCount(shopApplyHistoryDao.getTotalCount(queryString, params));
        pager.setList(accounts);
        return pager;
    }

    /**
     * 查询 门店申请对象
     *
     * @param id
     * @return
     */
    public ShopApplyHistory findApply(int id) {
        return shopApplyHistoryDao.load(id);
    }


}
